package com.lyx.fileio;

import java.io.*;

public class CopyFile {
    public static void main(String[] args) {
        copy("C:\\excel\\通讯录_20191126162840tgzw.xlsx","C:\\excel2",true);
    }


    public static boolean copy(String fromFileName, String toFileName, boolean override) {

        File fromFile = new File(fromFileName);
        File toFile = new File(toFileName);

        //isDirectory()测试此抽象路径名表示的文件是否为目录。
        if (!fromFile.exists() || !fromFile.isFile() || !fromFile.canRead()) {//isFile()测试此抽象路径名表示的文件是否为普通文件。
            return false;
        }
        if (toFile.isDirectory()) {//判断目标文件是否为目录
            toFile = new File(toFile, fromFile.getName());
        }
        if (toFile.exists()) {
            if (!toFile.canWrite() || override == false) {
                return false;
            }
        } else {
            //判断目标文件所在目录是否存在以及是否可写
            String parent = toFile.getParent();
            if (parent == null) {
                parent = System.getProperty("user.dir");
            }
            File dir = new File(parent);
            if (!dir.exists() || !dir.isFile() || !dir.canWrite()) {
                return false;
            }
        }
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytes_read;
            while ((bytes_read = from.read(buffer)) != -1) {
                to.write(buffer, 0, bytes_read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (from != null) {
                try {
                    from.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (to != null) {
                try {
                    to.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }



}
